home *** CD-ROM | disk | FTP | other *** search
/ MACD 5 / MACD 5.bin / workbench / libs / unixlib.lha / unix / src / regexp.c < prev    next >
C/C++ Source or Header  |  1996-04-27  |  31KB  |  1,296 lines

  1. /*
  2.  * regcomp and regexec -- regsub and regerror are elsewhere
  3.  *
  4.  *    Copyright (c) 1986 by University of Toronto.
  5.  *    Written by Henry Spencer.  Not derived from licensed software.
  6.  *
  7.  *    Permission is granted to anyone to use this software for any
  8.  *    purpose on any computer system, and to redistribute it freely,
  9.  *    subject to the following restrictions:
  10.  *
  11.  *    1. The author is not responsible for the consequences of use of
  12.  *        this software, no matter how awful, even if they arise
  13.  *        from defects in it.
  14.  *
  15.  *    2. The origin of this software must not be misrepresented, either
  16.  *        by explicit claim or by omission.
  17.  *
  18.  *    3. Altered versions must be plainly marked as such, and must not
  19.  *        be misrepresented as being the original software.
  20.  *** THIS IS AN ALTERED VERSION.  It was altered by John Gilmore,
  21.  *** hoptoad!gnu, on 27 Dec 1986, to add \n as an alternative to |
  22.  *** to assist in implementing egrep.
  23.  *** THIS IS AN ALTERED VERSION.  It was altered by John Gilmore,
  24.  *** hoptoad!gnu, on 27 Dec 1986, to add \< and \> for word-matching
  25.  *** as in BSD grep and ex.
  26.  *** THIS IS AN ALTERED VERSION.  It was altered by John Gilmore,
  27.  *** hoptoad!gnu, on 28 Dec 1986, to optimize characters quoted with \.
  28.  *** THIS IS AN ALTERED VERSION.  It was altered by James A. Woods,
  29.  *** ames!jaw, on 19 June 1987, to quash a regcomp() redundancy.
  30.  *
  31.  * Beware that some of this code is subtly aware of the way operator
  32.  * precedence is structured in regular expressions.  Serious changes in
  33.  * regular-expression syntax might require a total rethink.
  34.  */
  35. #include <regexp.h>
  36. #include <stdio.h>
  37. #include <ctype.h>
  38. #include <stdlib.h>
  39. #include <string.h>
  40. #include "regmagic.h"
  41.  
  42. /*
  43.  * The "internal use only" fields in regexp.h are present to pass info from
  44.  * compile to execute that permits the execute phase to run lots faster on
  45.  * simple cases.  They are:
  46.  *
  47.  * regstart    char that must begin a match; '\0' if none obvious
  48.  * reganch    is the match anchored (at beginning-of-line only)?
  49.  * regmust    string (pointer into program) that match must include, or NULL
  50.  * regmlen    length of regmust string
  51.  *
  52.  * Regstart and reganch permit very fast decisions on suitable starting points
  53.  * for a match, cutting down the work a lot.  Regmust permits fast rejection
  54.  * of lines that cannot possibly match.  The regmust tests are costly enough
  55.  * that regcomp() supplies a regmust only if the r.e. contains something
  56.  * potentially expensive (at present, the only such thing detected is * or +
  57.  * at the start of the r.e., which can involve a lot of backup).  Regmlen is
  58.  * supplied because the test in regexec() needs it and regcomp() is computing
  59.  * it anyway.
  60.  */
  61.  
  62. /*
  63.  * Structure for regexp "program".  This is essentially a linear encoding
  64.  * of a nondeterministic finite-state machine (aka syntax charts or
  65.  * "railroad normal form" in parsing technology).  Each node is an opcode
  66.  * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
  67.  * all nodes except BRANCH implement concatenation; a "next" pointer with
  68.  * a BRANCH on both ends of it is connecting two alternatives.  (Here we
  69.  * have one of the subtle syntax dependencies:  an individual BRANCH (as
  70.  * opposed to a collection of them) is never concatenated with anything
  71.  * because of operator precedence.)  The operand of some types of node is
  72.  * a literal string; for others, it is a node leading into a sub-FSM.  In
  73.  * particular, the operand of a BRANCH node is the first node of the branch.
  74.  * (NB this is *not* a tree structure:  the tail of the branch connects
  75.  * to the thing following the set of BRANCHes.)  The opcodes are:
  76.  */
  77.  
  78. /* definition    number    opnd?    meaning */
  79. #define    END    0    /* no    End of program. */
  80. #define    BOL    1    /* no    Match "" at beginning of line. */
  81. #define    EOL    2    /* no    Match "" at end of line. */
  82. #define    ANY    3    /* no    Match any one character. */
  83. #define    ANYOF    4    /* str    Match any character in this string. */
  84. #define    ANYBUT    5    /* str    Match any character not in this string. */
  85. #define    BRANCH    6    /* node    Match this alternative, or the next... */
  86. #define    BACK    7    /* no    Match "", "next" ptr points backward. */
  87. #define    EXACTLY    8    /* str    Match this string. */
  88. #define    NOTHING    9    /* no    Match empty string. */
  89. #define    STAR    10    /* node    Match this (simple) thing 0 or more times. */
  90. #define    PLUS    11    /* node    Match this (simple) thing 1 or more times. */
  91. #define    WORDA    12    /* no    Match "" at wordchar, where prev is nonword */
  92. #define    WORDZ    13    /* no    Match "" at nonwordchar, where prev is word */
  93. #define    OPEN    20    /* no    Mark this point in input as start of #n. */
  94.             /*    OPEN+1 is number 1, etc. */
  95. #define    CLOSE    30    /* no    Analogous to OPEN. */
  96.  
  97. /*
  98.  * Opcode notes:
  99.  *
  100.  * BRANCH    The set of branches constituting a single choice are hooked
  101.  *        together with their "next" pointers, since precedence prevents
  102.  *        anything being concatenated to any individual branch.  The
  103.  *        "next" pointer of the last BRANCH in a choice points to the
  104.  *        thing following the whole choice.  This is also where the
  105.  *        final "next" pointer of each individual branch points; each
  106.  *        branch starts with the operand node of a BRANCH node.
  107.  *
  108.  * BACK        Normal "next" pointers all implicitly point forward; BACK
  109.  *        exists to make loop structures possible.
  110.  *
  111.  * STAR,PLUS    '?', and complex '*' and '+', are implemented as circular
  112.  *        BRANCH structures using BACK.  Simple cases (one character
  113.  *        per match) are implemented with STAR and PLUS for speed
  114.  *        and to minimize recursive plunges.
  115.  *
  116.  * OPEN,CLOSE    ...are numbered at compile time.
  117.  */
  118.  
  119. /*
  120.  * A node is one char of opcode followed by two chars of "next" pointer.
  121.  * "Next" pointers are stored as two 8-bit pieces, high order first.  The
  122.  * value is a positive offset from the opcode of the node containing it.
  123.  * An operand, if any, simply follows the node.  (Note that much of the
  124.  * code generation knows about this implicit relationship.)
  125.  *
  126.  * Using two bytes for the "next" pointer is vast overkill for most things,
  127.  * but allows patterns to get big without disasters.
  128.  */
  129. #define    OP(p)    (*(p))
  130. #define    NEXT(p)    (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
  131. #define    OPERAND(p)    ((p) + 3)
  132.  
  133. /*
  134.  * See regmagic.h for one further detail of program structure.
  135.  */
  136.  
  137.  
  138. /*
  139.  * Utility definitions.
  140.  */
  141. #ifndef CHARBITS
  142. #define    UCHARAT(p)    ((int)*(unsigned char *)(p))
  143. #else
  144. #define    UCHARAT(p)    ((int)*(p)&CHARBITS)
  145. #endif
  146.  
  147. #define    FAIL(m)    { regerror(m); return(NULL); }
  148. #define    ISMULT(c)    ((c) == '*' || (c) == '+' || (c) == '?')
  149.  
  150. /*
  151.  * Flags to be passed up and down.
  152.  */
  153. #define    HASWIDTH    01    /* Known never to match null string. */
  154. #define    SIMPLE        02    /* Simple enough to be STAR/PLUS operand. */
  155. #define    SPSTART        04    /* Starts with * or +. */
  156. #define    WORST        0    /* Worst case. */
  157.  
  158. /*
  159.  * Global work variables for regcomp().
  160.  */
  161. static char *regparse;        /* Input-scan pointer. */
  162. static int regnpar;        /* () count. */
  163. static char regdummy;
  164. static char *regcode;        /* Code-emit pointer; ®dummy = don't. */
  165. static long regsize;        /* Code size. */
  166.  
  167. /*
  168.  * Forward declarations for regcomp()'s friends.
  169.  */
  170. #ifndef STATIC
  171. #define    STATIC    static
  172. #endif
  173. STATIC char *reg(int, int *);
  174. STATIC char *regbranch(int *);
  175. STATIC char *regpiece(int *);
  176. STATIC char *regatom(int *);
  177. STATIC char *regnode(char);
  178. STATIC char *regnext(register char *);
  179. STATIC void regc(char);
  180. STATIC void reginsert(char, char *);
  181. STATIC void regtail(char *, char *);
  182. STATIC void regoptail(char *, char *);
  183. #ifdef STRCSPN
  184. STATIC int strcspn(char *, char *);
  185. #endif
  186.  
  187. /*
  188.  - regcomp - compile a regular expression into internal code
  189.  *
  190.  * We can't allocate space until we know how big the compiled form will be,
  191.  * but we can't compile it (and thus know how big it is) until we've got a
  192.  * place to put the code.  So we cheat:  we compile it twice, once with code
  193.  * generation turned off and size counting turned on, and once "for real".
  194.  * This also means that we don't allocate space until we are sure that the
  195.  * thing really will compile successfully, and we never have to move the
  196.  * code and thus invalidate pointers into it.  (Note that it has to be in
  197.  * one piece because free() must be able to free it all.)
  198.  *
  199.  * Beware that the optimization-preparation code in here knows about some
  200.  * of the structure of the compiled regexp.
  201.  */
  202. regexp *
  203. regcomp(const char *exp)
  204. {
  205.     register regexp *r;
  206.     register char *scan;
  207.     register char *longest;
  208.     register int len;
  209.     int flags;
  210.  
  211.     if (exp == NULL)
  212.         FAIL("NULL argument");
  213.  
  214.     /* First pass: determine size, legality. */
  215. #ifdef notdef
  216.     if (exp[0] == '.' && exp[1] == '*') exp += 2;  /* aid grep */
  217. #endif
  218.     regparse = (char *)exp;
  219.     regnpar = 1;
  220.     regsize = 0L;
  221.     regcode = ®dummy;
  222.     regc((unsigned char)MAGIC);
  223.     if (reg(0, &flags) == NULL)
  224.         return(NULL);
  225.  
  226.     /* Small enough for pointer-storage convention? */
  227.     if (regsize >= 32767L)        /* Probably could be 65535L. */
  228.         FAIL("regexp too big");
  229.  
  230.     /* Allocate space. */
  231.     r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize);
  232.     if (r == NULL)
  233.         FAIL("out of space");
  234.  
  235.     /* Second pass: emit code. */
  236.     regparse = (char *)exp;
  237.     regnpar = 1;
  238.     regcode = r->program;
  239.     regc((unsigned char)MAGIC);
  240.     if (reg(0, &flags) == NULL)
  241.         return(NULL);
  242.  
  243.     /* Dig out information for optimizations. */
  244.     r->regstart = '\0';    /* Worst-case defaults. */
  245.     r->reganch = 0;
  246.     r->regmust = NULL;
  247.     r->regmlen = 0;
  248.     scan = r->program+1;            /* First BRANCH. */
  249.     if (OP(regnext(scan)) == END) {        /* Only one top-level choice. */
  250.         scan = OPERAND(scan);
  251.  
  252.         /* Starting-point info. */
  253.         if (OP(scan) == EXACTLY)
  254.             r->regstart = *OPERAND(scan);
  255.         else if (OP(scan) == BOL)
  256.             r->reganch++;
  257.  
  258.         /*
  259.          * If there's something expensive in the r.e., find the
  260.          * longest literal string that must appear and make it the
  261.          * regmust.  Resolve ties in favor of later strings, since
  262.          * the regstart check works with the beginning of the r.e.
  263.          * and avoiding duplication strengthens checking.  Not a
  264.          * strong reason, but sufficient in the absence of others.
  265.          */
  266.         if (flags&SPSTART) {
  267.             longest = NULL;
  268.             len = 0;
  269.             for (; scan != NULL; scan = regnext(scan))
  270.                 if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
  271.                     longest = OPERAND(scan);
  272.                     len = strlen(OPERAND(scan));
  273.                 }
  274.             r->regmust = longest;
  275.             r->regmlen = len;
  276.         }
  277.     }
  278.  
  279.     return(r);
  280. }
  281.  
  282. /*
  283.  - reg - regular expression, i.e. main body or parenthesized thing
  284.  *
  285.  * Caller must absorb opening parenthesis.
  286.  *
  287.  * Combining parenthesis handling with the base level of regular expression
  288.  * is a trifle forced, but the need to tie the tails of the branches to what
  289.  * follows makes it hard to avoid.
  290.  */
  291. static char *
  292. reg(int paren /* Parenthesized? */, int *flagp)
  293. {
  294.     register char *ret;
  295.     register char *br;
  296.     register char *ender;
  297.         register int parno = 0;
  298.     int flags;
  299.  
  300.     *flagp = HASWIDTH;    /* Tentatively. */
  301.  
  302.     /* Make an OPEN node, if parenthesized. */
  303.     if (paren) {
  304.         if (regnpar >= NSUBEXP)
  305.             FAIL("too many ()");
  306.         parno = regnpar;
  307.         regnpar++;
  308.         ret = regnode(OPEN+parno);
  309.     } else
  310.         ret = NULL;
  311.  
  312.     /* Pick up the branches, linking them together. */
  313.     br = regbranch(&flags);
  314.     if (br == NULL)
  315.         return(NULL);
  316.     if (ret != NULL)
  317.         regtail(ret, br);    /* OPEN -> first. */
  318.     else
  319.         ret = br;
  320.     if (!(flags&HASWIDTH))
  321.         *flagp &= ~HASWIDTH;
  322.     *flagp |= flags&SPSTART;
  323.     while (*regparse == '|' || *regparse == '\n') {
  324.         regparse++;
  325.         br = regbranch(&flags);
  326.         if (br == NULL)
  327.             return(NULL);
  328.         regtail(ret, br);    /* BRANCH -> BRANCH. */
  329.         if (!(flags&HASWIDTH))
  330.             *flagp &= ~HASWIDTH;
  331.         *flagp |= flags&SPSTART;
  332.     }
  333.  
  334.     /* Make a closing node, and hook it on the end. */
  335.     ender = regnode((paren) ? CLOSE+parno : END);    
  336.     regtail(ret, ender);
  337.  
  338.     /* Hook the tails of the branches to the closing node. */
  339.     for (br = ret; br != NULL; br = regnext(br))
  340.         regoptail(br, ender);
  341.  
  342.     /* Check for proper termination. */
  343.     if (paren && *regparse++ != ')') {
  344.         FAIL("unmatched ()");
  345.     } else if (!paren && *regparse != '\0') {
  346.         if (*regparse == ')') {
  347.             FAIL("unmatched ()");
  348.         } else
  349.             FAIL("junk on end");    /* "Can't happen". */
  350.         /* NOTREACHED */
  351.     }
  352.  
  353.     return(ret);
  354. }
  355.  
  356. /*
  357.  - regbranch - one alternative of an | operator
  358.  *
  359.  * Implements the concatenation operator.
  360.  */
  361. static char *
  362. regbranch(int *flagp)
  363. {
  364.     register char *ret;
  365.     register char *chain;
  366.     register char *latest;
  367.     int flags;
  368.  
  369.     *flagp = WORST;        /* Tentatively. */
  370.  
  371.     ret = regnode(BRANCH);
  372.     chain = NULL;
  373.     while (*regparse != '\0' && *regparse != ')' &&
  374.            *regparse != '\n' && *regparse != '|') {
  375.         latest = regpiece(&flags);
  376.         if (latest == NULL)
  377.             return(NULL);
  378.         *flagp |= flags&HASWIDTH;
  379.         if (chain == NULL)    /* First piece. */
  380.             *flagp |= flags&SPSTART;
  381.         else
  382.             regtail(chain, latest);
  383.         chain = latest;
  384.     }
  385.     if (chain == NULL)    /* Loop ran zero times. */
  386.         (void) regnode(NOTHING);
  387.  
  388.     return(ret);
  389. }
  390.  
  391. /*
  392.  - regpiece - something followed by possible [*+?]
  393.  *
  394.  * Note that the branching code sequences used for ? and the general cases
  395.  * of * and + are somewhat optimized:  they use the same NOTHING node as
  396.  * both the endmarker for their branch list and the body of the last branch.
  397.  * It might seem that this node could be dispensed with entirely, but the
  398.  * endmarker role is not redundant.
  399.  */
  400. static char *
  401. regpiece(int *flagp)
  402. {
  403.     register char *ret;
  404.     register char op;
  405.     register char *next;
  406.     int flags;
  407.  
  408.     ret = regatom(&flags);
  409.     if (ret == NULL)
  410.         return(NULL);
  411.  
  412.     op = *regparse;
  413.     if (!ISMULT(op)) {
  414.         *flagp = flags;
  415.         return(ret);
  416.     }
  417.  
  418.     if (!(flags&HASWIDTH) && op != '?')
  419.         FAIL("*+ operand could be empty");
  420.     *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
  421.  
  422.     if (op == '*' && (flags&SIMPLE))
  423.         reginsert(STAR, ret);
  424.     else if (op == '*') {
  425.         /* Emit x* as (x&|), where & means "self". */
  426.         reginsert(BRANCH, ret);            /* Either x */
  427.         regoptail(ret, regnode(BACK));        /* and loop */
  428.         regoptail(ret, ret);            /* back */
  429.         regtail(ret, regnode(BRANCH));        /* or */
  430.         regtail(ret, regnode(NOTHING));        /* null. */
  431.     } else if (op == '+' && (flags&SIMPLE))
  432.         reginsert(PLUS, ret);
  433.     else if (op == '+') {
  434.         /* Emit x+ as x(&|), where & means "self". */
  435.         next = regnode(BRANCH);            /* Either */
  436.         regtail(ret, next);
  437.         regtail(regnode(BACK), ret);        /* loop back */
  438.         regtail(next, regnode(BRANCH));        /* or */
  439.         regtail(ret, regnode(NOTHING));        /* null. */
  440.     } else if (op == '?') {
  441.         /* Emit x? as (x|) */
  442.         reginsert(BRANCH, ret);            /* Either x */
  443.         regtail(ret, regnode(BRANCH));        /* or */
  444.         next = regnode(NOTHING);        /* null. */
  445.         regtail(ret, next);
  446.         regoptail(ret, next);
  447.     }
  448.     regparse++;
  449.     if (ISMULT(*regparse))
  450.         FAIL("nested *?+");
  451.  
  452.     return(ret);
  453. }
  454.  
  455. /*
  456.  - regatom - the lowest level
  457.  *
  458.  * Optimization:  gobbles an entire sequence of ordinary characters so that
  459.  * it can turn them into a single node, which is smaller to store and
  460.  * faster to run.  Backslashed characters are exceptions, each becoming a
  461.  * separate node; the code is simpler that way and it's not worth fixing.
  462.  */
  463. static char *
  464. regatom(int *flagp)
  465. {
  466.     register char *ret;
  467.     int flags;
  468.  
  469.     *flagp = WORST;        /* Tentatively. */
  470.  
  471.     switch (*regparse++) {
  472.     /* FIXME: these chars only have meaning at beg/end of pat? */
  473.     case '^':
  474.         ret = regnode(BOL);
  475.         break;
  476.     case '$':
  477.         ret = regnode(EOL);
  478.         break;
  479.     case '.':
  480.         ret = regnode(ANY);
  481.         *flagp |= HASWIDTH|SIMPLE;
  482.         break;
  483.     case '[': {
  484.             register int class;
  485.             register int classend;
  486.  
  487.             if (*regparse == '^') {    /* Complement of range. */
  488.                 ret = regnode(ANYBUT);
  489.                 regparse++;
  490.             } else
  491.                 ret = regnode(ANYOF);
  492.             if (*regparse == ']' || *regparse == '-')
  493.                 regc(*regparse++);
  494.             while (*regparse != '\0' && *regparse != ']') {
  495.                 if (*regparse == '-') {
  496.                     regparse++;
  497.                     if (*regparse == ']' || *regparse == '\0')
  498.                         regc('-');
  499.                     else {
  500.                         class = UCHARAT(regparse-2)+1;
  501.                         classend = UCHARAT(regparse);
  502.                         if (class > classend+1)
  503.                             FAIL("invalid [] range");
  504.                         for (; class <= classend; class++)
  505.                             regc(class);
  506.                         regparse++;
  507.                     }
  508.                 } else
  509.                     regc(*regparse++);
  510.             }
  511.             regc('\0');
  512.             if (*regparse != ']')
  513.                 FAIL("unmatched []");
  514.             regparse++;
  515.             *flagp |= HASWIDTH|SIMPLE;
  516.         }
  517.         break;
  518.     case '(':
  519.         ret = reg(1, &flags);
  520.         if (ret == NULL)
  521.             return(NULL);
  522.         *flagp |= flags&(HASWIDTH|SPSTART);
  523.         break;
  524.     case '\0':
  525.     case '|':
  526.     case '\n':
  527.     case ')':
  528.         FAIL("internal urp");    /* Supposed to be caught earlier. */
  529.         break;
  530.     case '?':
  531.     case '+':
  532.     case '*':
  533.         FAIL("?+* follows nothing");
  534.         break;
  535.     case '\\':
  536.         switch (*regparse++) {
  537.         case '\0':
  538.             FAIL("trailing \\");
  539.             break;
  540.         case '<':
  541.             ret = regnode(WORDA);
  542.             break;
  543.         case '>':
  544.             ret = regnode(WORDZ);
  545.             break;
  546.         /* FIXME: Someday handle \1, \2, ... */
  547.         default:
  548.             /* Handle general quoted chars in exact-match routine */
  549.             goto de_fault;
  550.         }
  551.         break;
  552.     de_fault:
  553.     default:
  554.         /*
  555.          * Encode a string of characters to be matched exactly.
  556.          *
  557.          * This is a bit tricky due to quoted chars and due to
  558.          * '*', '+', and '?' taking the SINGLE char previous
  559.          * as their operand.
  560.          *
  561.          * On entry, the char at regparse[-1] is going to go
  562.          * into the string, no matter what it is.  (It could be
  563.          * following a \ if we are entered from the '\' case.)
  564.          * 
  565.          * Basic idea is to pick up a good char in  ch  and
  566.          * examine the next char.  If it's *+? then we twiddle.
  567.          * If it's \ then we frozzle.  If it's other magic char
  568.          * we push  ch  and terminate the string.  If none of the
  569.          * above, we push  ch  on the string and go around again.
  570.          *
  571.          *  regprev  is used to remember where "the current char"
  572.          * starts in the string, if due to a *+? we need to back
  573.          * up and put the current char in a separate, 1-char, string.
  574.          * When  regprev  is NULL,  ch  is the only char in the
  575.          * string; this is used in *+? handling, and in setting
  576.          * flags |= SIMPLE at the end.
  577.          */
  578.         {
  579.             char *regprev;
  580.             register char ch;
  581.  
  582.             regparse--;            /* Look at cur char */
  583.             ret = regnode(EXACTLY);
  584.             for ( regprev = 0 ; ; ) {
  585.                 ch = *regparse++;    /* Get current char */
  586.                 switch (*regparse) {    /* look at next one */
  587.  
  588.                 default:
  589.                     regc(ch);    /* Add cur to string */
  590.                     break;
  591.  
  592.                 case '.': case '[': case '(':
  593.                 case ')': case '|': case '\n':
  594.                 case '$': case '^':
  595.                 case '\0':
  596.                 /* FIXME, $ and ^ should not always be magic */
  597.                 magic:
  598.                     regc(ch);    /* dump cur char */
  599.                     goto done;    /* and we are done */
  600.  
  601.                 case '?': case '+': case '*':
  602.                     if (!regprev)     /* If just ch in str, */
  603.                         goto magic;    /* use it */
  604.                     /* End mult-char string one early */
  605.                     regparse = regprev; /* Back up parse */
  606.                     goto done;
  607.  
  608.                 case '\\':
  609.                     regc(ch);    /* Cur char OK */
  610.                     switch (regparse[1]){ /* Look after \ */
  611.                     case '\0':
  612.                     case '<':
  613.                     case '>':
  614.                     /* FIXME: Someday handle \1, \2, ... */
  615.                         goto done; /* Not quoted */
  616.                     default:
  617.                         /* Backup point is \, scan                             * point is after it. */
  618.                         regprev = regparse;
  619.                         regparse++; 
  620.                         continue;    /* NOT break; */
  621.                     }
  622.                 }
  623.                 regprev = regparse;    /* Set backup point */
  624.             }
  625.         done:
  626.             regc('\0');
  627.             *flagp |= HASWIDTH;
  628.             if (!regprev)        /* One char? */
  629.                 *flagp |= SIMPLE;
  630.         }
  631.         break;
  632.     }
  633.  
  634.     return(ret);
  635. }
  636.  
  637. /*
  638.  - regnode - emit a node
  639.  */
  640. static char *            /* Location. */
  641. regnode(char op)
  642. {
  643.     register char *ret;
  644.     register char *ptr;
  645.  
  646.     ret = regcode;
  647.     if (ret == ®dummy) {
  648.         regsize += 3;
  649.         return(ret);
  650.     }
  651.  
  652.     ptr = ret;
  653.     *ptr++ = op;
  654.     *ptr++ = '\0';        /* Null "next" pointer. */
  655.     *ptr++ = '\0';
  656.     regcode = ptr;
  657.  
  658.     return(ret);
  659. }
  660.  
  661. /*
  662.  - regc - emit (if appropriate) a byte of code
  663.  */
  664. static void
  665. regc(char b)
  666. {
  667.     if (regcode != ®dummy)
  668.         *regcode++ = b;
  669.     else
  670.         regsize++;
  671. }
  672.  
  673. /*
  674.  - reginsert - insert an operator in front of already-emitted operand
  675.  *
  676.  * Means relocating the operand.
  677.  */
  678. static void
  679. reginsert(char op, char *opnd)
  680. {
  681.     register char *src;
  682.     register char *dst;
  683.     register char *place;
  684.  
  685.     if (regcode == ®dummy) {
  686.         regsize += 3;
  687.         return;
  688.     }
  689.  
  690.     src = regcode;
  691.     regcode += 3;
  692.     dst = regcode;
  693.     while (src > opnd)
  694.         *--dst = *--src;
  695.  
  696.     place = opnd;        /* Op node, where operand used to be. */
  697.     *place++ = op;
  698.     *place++ = '\0';
  699.     *place = '\0';
  700. }
  701.  
  702. /*
  703.  - regtail - set the next-pointer at the end of a node chain
  704.  */
  705. static void
  706. regtail(char *p, char *val)
  707. {
  708.     register char *scan;
  709.     register char *temp;
  710.     register int offset;
  711.  
  712.     if (p == ®dummy)
  713.         return;
  714.  
  715.     /* Find last node. */
  716.     scan = p;
  717.     for (;;) {
  718.         temp = regnext(scan);
  719.         if (temp == NULL)
  720.             break;
  721.         scan = temp;
  722.     }
  723.  
  724.     if (OP(scan) == BACK)
  725.         offset = scan - val;
  726.     else
  727.         offset = val - scan;
  728.     *(scan+1) = (offset>>8)&0377;
  729.     *(scan+2) = offset&0377;
  730. }
  731.  
  732. /*
  733.  - regoptail - regtail on operand of first argument; nop if operandless
  734.  */
  735. static void
  736. regoptail(char *p, char *val)
  737. {
  738.     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
  739.     if (p == NULL || p == ®dummy || OP(p) != BRANCH)
  740.         return;
  741.     regtail(OPERAND(p), val);
  742. }
  743.  
  744. /*
  745.  * regexec and friends
  746.  */
  747.  
  748. /*
  749.  * Global work variables for regexec().
  750.  */
  751. static char *reginput;        /* String-input pointer. */
  752. static char *regbol;        /* Beginning of input, for ^ check. */
  753. static char **regstartp;    /* Pointer to startp array. */
  754. static char **regendp;        /* Ditto for endp. */
  755.  
  756. /*
  757.  * Forwards.
  758.  */
  759. STATIC int regtry(regexp *, char *);
  760. STATIC int regmatch(char *);
  761. STATIC int regrepeat(char *);
  762.  
  763. #ifdef DEBUG
  764. int regnarrate = 0;
  765. void regdump(regexp *);
  766. STATIC char *regprop(char *);
  767. #endif
  768.  
  769. /*
  770.  - regexec - match a regexp against a string
  771.  */
  772. int
  773. regexec(register const regexp *prog, register const char *string)
  774. {
  775.     register char *s;
  776.     extern char *strchr(const char *, int);
  777.  
  778.     /* Be paranoid... */
  779.     if (prog == NULL || string == NULL) {
  780.         regerror("NULL parameter");
  781.         return(0);
  782.     }
  783.  
  784.     /* Check validity of program. */
  785.     if (UCHARAT(prog->program) != MAGIC) {
  786.         regerror("corrupted program");
  787.         return(0);
  788.     }
  789.  
  790.     /* If there is a "must appear" string, look for it. */
  791.     if (prog->regmust != NULL) {
  792.         s = (char *)string;
  793.         while ((s = strchr(s, prog->regmust[0])) != NULL) {
  794.             if (strncmp(s, prog->regmust, prog->regmlen) == 0)
  795.                 break;    /* Found it. */
  796.             s++;
  797.         }
  798.         if (s == NULL)    /* Not present. */
  799.             return(0);
  800.     }
  801.  
  802.     /* Mark beginning of line for ^ . */
  803.     regbol = (char *)string;
  804.  
  805.     /* Simplest case:  anchored match need be tried only once. */
  806.     if (prog->reganch)
  807.         return(regtry(prog, string));
  808.  
  809.     /* Messy cases:  unanchored match. */
  810.     s = (char *)string;
  811.     if (prog->regstart != '\0')
  812.         /* We know what char it must start with. */
  813.         while ((s = strchr(s, prog->regstart)) != NULL) {
  814.             if (regtry(prog, s))
  815.                 return(1);
  816.             s++;
  817.         }
  818.     else
  819.         /* We don't -- general case. */
  820.         do {
  821.             if (regtry(prog, s))
  822.                 return(1);
  823.         } while (*s++ != '\0');
  824.  
  825.     /* Failure. */
  826.     return(0);
  827. }
  828.  
  829. /*
  830.  - regtry - try match at specific point
  831.  */
  832. static int            /* 0 failure, 1 success */
  833. regtry(regexp *prog, char *string)
  834. {
  835.     register int i;
  836.     register char **sp;
  837.     register char **ep;
  838.  
  839.     reginput = string;
  840.     regstartp = prog->startp;
  841.     regendp = prog->endp;
  842.  
  843.     sp = prog->startp;
  844.     ep = prog->endp;
  845.     for (i = NSUBEXP; i > 0; i--) {
  846.         *sp++ = NULL;
  847.         *ep++ = NULL;
  848.     }
  849.     if (regmatch(prog->program + 1)) {
  850.         prog->startp[0] = string;
  851.         prog->endp[0] = reginput;
  852.         return(1);
  853.     } else
  854.         return(0);
  855. }
  856.  
  857. /*
  858.  - regmatch - main matching routine
  859.  *
  860.  * Conceptually the strategy is simple:  check to see whether the current
  861.  * node matches, call self recursively to see whether the rest matches,
  862.  * and then act accordingly.  In practice we make some effort to avoid
  863.  * recursion, in particular by going through "ordinary" nodes (that don't
  864.  * need to know whether the rest of the match failed) by a loop instead of
  865.  * by recursion.
  866.  */
  867. static int            /* 0 failure, 1 success */
  868. regmatch(char *prog)
  869. {
  870.     register char *scan;    /* Current node. */
  871.     char *next;        /* Next node. */
  872.     extern char *strchr(const char *, int);
  873.  
  874.     scan = prog;
  875. #ifdef DEBUG
  876.     if (scan != NULL && regnarrate)
  877.         fprintf(stderr, "%s(\n", regprop(scan));
  878. #endif
  879.     while (scan != NULL) {
  880. #ifdef DEBUG
  881.         if (regnarrate)
  882.             fprintf(stderr, "%s...\n", regprop(scan));
  883. #endif
  884.         next = regnext(scan);
  885.  
  886.         switch (OP(scan)) {
  887.         case BOL:
  888.             if (reginput != regbol)
  889.                 return(0);
  890.             break;
  891.         case EOL:
  892.             if (*reginput != '\0')
  893.                 return(0);
  894.             break;
  895.         case WORDA:
  896.             /* Must be looking at a letter, digit, or _ */
  897.             if ((!isalnum(*reginput)) && *reginput != '_')
  898.                 return(0);
  899.             /* Prev must be BOL or nonword */
  900.             if (reginput > regbol &&
  901.                 (isalnum(reginput[-1]) || reginput[-1] == '_'))
  902.                 return(0);
  903.             break;
  904.         case WORDZ:
  905.             /* Must be looking at non letter, digit, or _ */
  906.             if (isalnum(*reginput) || *reginput == '_')
  907.                 return(0);
  908.             /* We don't care what the previous char was */
  909.             break;
  910.         case ANY:
  911.             if (*reginput == '\0')
  912.                 return(0);
  913.             reginput++;
  914.             break;
  915.         case EXACTLY: {
  916.                 register int len;
  917.                 register char *opnd;
  918.  
  919.                 opnd = OPERAND(scan);
  920.                 /* Inline the first character, for speed. */
  921.                 if (*opnd != *reginput)
  922.                     return(0);
  923.                 len = strlen(opnd);
  924.                 if (len > 1 && strncmp(opnd, reginput, len) != 0)
  925.                     return(0);
  926.                 reginput += len;
  927.             }
  928.             break;
  929.         case ANYOF:
  930.              if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL)
  931.                 return(0);
  932.             reginput++;
  933.             break;
  934.         case ANYBUT:
  935.              if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL)
  936.                 return(0);
  937.             reginput++;
  938.             break;
  939.         case NOTHING:
  940.             break;
  941.         case BACK:
  942.             break;
  943.         case OPEN+1:
  944.         case OPEN+2:
  945.         case OPEN+3:
  946.         case OPEN+4:
  947.         case OPEN+5:
  948.         case OPEN+6:
  949.         case OPEN+7:
  950.         case OPEN+8:
  951.         case OPEN+9: {
  952.                 register int no;
  953.                 register char *save;
  954.  
  955.                 no = OP(scan) - OPEN;
  956.                 save = reginput;
  957.  
  958.                 if (regmatch(next)) {
  959.                     /*
  960.                      * Don't set startp if some later
  961.                      * invocation of the same parentheses
  962.                      * already has.
  963.                      */
  964.                     if (regstartp[no] == NULL)
  965.                         regstartp[no] = save;
  966.                     return(1);
  967.                 } else
  968.                     return(0);
  969.             }
  970.             break;
  971.         case CLOSE+1:
  972.         case CLOSE+2:
  973.         case CLOSE+3:
  974.         case CLOSE+4:
  975.         case CLOSE+5:
  976.         case CLOSE+6:
  977.         case CLOSE+7:
  978.         case CLOSE+8:
  979.         case CLOSE+9: {
  980.                 register int no;
  981.                 register char *save;
  982.  
  983.                 no = OP(scan) - CLOSE;
  984.                 save = reginput;
  985.  
  986.                 if (regmatch(next)) {
  987.                     /*
  988.                      * Don't set endp if some later
  989.                      * invocation of the same parentheses
  990.                      * already has.
  991.                      */
  992.                     if (regendp[no] == NULL)
  993.                         regendp[no] = save;
  994.                     return(1);
  995.                 } else
  996.                     return(0);
  997.             }
  998.             break;
  999.         case BRANCH: {
  1000.                 register char *save;
  1001.  
  1002.                 if (OP(next) != BRANCH)        /* No choice. */
  1003.                     next = OPERAND(scan);    /* Avoid recursion. */
  1004.                 else {
  1005.                     do {
  1006.                         save = reginput;
  1007.                         if (regmatch(OPERAND(scan)))
  1008.                             return(1);
  1009.                         reginput = save;
  1010.                         scan = regnext(scan);
  1011.                     } while (scan != NULL && OP(scan) == BRANCH);
  1012.                     return(0);
  1013.                     /* NOTREACHED */
  1014.                 }
  1015.             }
  1016.             break;
  1017.         case STAR:
  1018.         case PLUS: {
  1019.                 register char nextch;
  1020.                 register int no;
  1021.                 register char *save;
  1022.                 register int min;
  1023.  
  1024.                 /*
  1025.                  * Lookahead to avoid useless match attempts
  1026.                  * when we know what character comes next.
  1027.                  */
  1028.                 nextch = '\0';
  1029.                 if (OP(next) == EXACTLY)
  1030.                     nextch = *OPERAND(next);
  1031.                 min = (OP(scan) == STAR) ? 0 : 1;
  1032.                 save = reginput;
  1033.                 no = regrepeat(OPERAND(scan));
  1034.                 while (no >= min) {
  1035.                     /* If it could work, try it. */
  1036.                     if (nextch == '\0' || *reginput == nextch)
  1037.                         if (regmatch(next))
  1038.                             return(1);
  1039.                     /* Couldn't or didn't -- back up. */
  1040.                     no--;
  1041.                     reginput = save + no;
  1042.                 }
  1043.                 return(0);
  1044.             }
  1045.             break;
  1046.         case END:
  1047.             return(1);    /* Success! */
  1048.             break;
  1049.         default:
  1050.             regerror("memory corruption");
  1051.             return(0);
  1052.             break;
  1053.         }
  1054.  
  1055.         scan = next;
  1056.     }
  1057.  
  1058.     /*
  1059.      * We get here only if there's trouble -- normally "case END" is
  1060.      * the terminating point.
  1061.      */
  1062.     regerror("corrupted pointers");
  1063.     return(0);
  1064. }
  1065.  
  1066. /*
  1067.  - regrepeat - repeatedly match something simple, report how many
  1068.  */
  1069. static int
  1070. regrepeat(char *p)
  1071. {
  1072.     register int count = 0;
  1073.     register char *scan;
  1074.     register char *opnd;
  1075.  
  1076.     scan = reginput;
  1077.     opnd = OPERAND(p);
  1078.     switch (OP(p)) {
  1079.     case ANY:
  1080.         count = strlen(scan);
  1081.         scan += count;
  1082.         break;
  1083.     case EXACTLY:
  1084.         while (*opnd == *scan) {
  1085.             count++;
  1086.             scan++;
  1087.         }
  1088.         break;
  1089.     case ANYOF:
  1090.         while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
  1091.             count++;
  1092.             scan++;
  1093.         }
  1094.         break;
  1095.     case ANYBUT:
  1096.         while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
  1097.             count++;
  1098.             scan++;
  1099.         }
  1100.         break;
  1101.     default:        /* Oh dear.  Called inappropriately. */
  1102.         regerror("internal foulup");
  1103.         count = 0;    /* Best compromise. */
  1104.         break;
  1105.     }
  1106.     reginput = scan;
  1107.  
  1108.     return(count);
  1109. }
  1110.  
  1111. /*
  1112.  - regnext - dig the "next" pointer out of a node
  1113.  */
  1114. static char *
  1115. regnext(register char *p)
  1116. {
  1117.     register int offset;
  1118.  
  1119.     if (p == ®dummy)
  1120.         return(NULL);
  1121.  
  1122.     offset = NEXT(p);
  1123.     if (offset == 0)
  1124.         return(NULL);
  1125.  
  1126.     if (OP(p) == BACK)
  1127.         return(p-offset);
  1128.     else
  1129.         return(p+offset);
  1130. }
  1131.  
  1132. #ifdef DEBUG
  1133.  
  1134. STATIC char *regprop(char *);
  1135.  
  1136. /*
  1137.  - regdump - dump a regexp onto stdout in vaguely comprehensible form
  1138.  */
  1139. void
  1140. regdump(regexp *r)
  1141. {
  1142.     register char *s;
  1143.     register char op = EXACTLY;    /* Arbitrary non-END op. */
  1144.     register char *next;
  1145.     extern char *strchr(const char *, int);
  1146.  
  1147.  
  1148.     s = r->program + 1;
  1149.     while (op != END) {    /* While that wasn't END last time... */
  1150.         op = OP(s);
  1151.         printf("%2d%s", s-r->program, regprop(s));    /* Where, what. */
  1152.         next = regnext(s);
  1153.         if (next == NULL)        /* Next ptr. */
  1154.             printf("(0)");
  1155.         else 
  1156.             printf("(%d)", (s-r->program)+(next-s));
  1157.         s += 3;
  1158.         if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
  1159.             /* Literal string, where present. */
  1160.             while (*s != '\0') {
  1161.                 putchar(*s);
  1162.                 s++;
  1163.             }
  1164.             s++;
  1165.         }
  1166.         putchar('\n');
  1167.     }
  1168.  
  1169.     /* Header fields of interest. */
  1170.     if (r->regstart != '\0')
  1171.         printf("start `%c' ", r->regstart);
  1172.     if (r->reganch)
  1173.         printf("anchored ");
  1174.     if (r->regmust != NULL)
  1175.         printf("must have \"%s\"", r->regmust);
  1176.     printf("\n");
  1177. }
  1178.  
  1179. /*
  1180.  - regprop - printable representation of opcode
  1181.  */
  1182. static char *
  1183. regprop(char *op)
  1184. {
  1185.     register char *p;
  1186.     static char buf[50];
  1187.  
  1188.     (void) strcpy(buf, ":");
  1189.  
  1190.     switch (OP(op)) {
  1191.     case BOL:
  1192.         p = "BOL";
  1193.         break;
  1194.     case EOL:
  1195.         p = "EOL";
  1196.         break;
  1197.     case ANY:
  1198.         p = "ANY";
  1199.         break;
  1200.     case ANYOF:
  1201.         p = "ANYOF";
  1202.         break;
  1203.     case ANYBUT:
  1204.         p = "ANYBUT";
  1205.         break;
  1206.     case BRANCH:
  1207.         p = "BRANCH";
  1208.         break;
  1209.     case EXACTLY:
  1210.         p = "EXACTLY";
  1211.         break;
  1212.     case NOTHING:
  1213.         p = "NOTHING";
  1214.         break;
  1215.     case BACK:
  1216.         p = "BACK";
  1217.         break;
  1218.     case END:
  1219.         p = "END";
  1220.         break;
  1221.     case OPEN+1:
  1222.     case OPEN+2:
  1223.     case OPEN+3:
  1224.     case OPEN+4:
  1225.     case OPEN+5:
  1226.     case OPEN+6:
  1227.     case OPEN+7:
  1228.     case OPEN+8:
  1229.     case OPEN+9:
  1230.         sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
  1231.         p = NULL;
  1232.         break;
  1233.     case CLOSE+1:
  1234.     case CLOSE+2:
  1235.     case CLOSE+3:
  1236.     case CLOSE+4:
  1237.     case CLOSE+5:
  1238.     case CLOSE+6:
  1239.     case CLOSE+7:
  1240.     case CLOSE+8:
  1241.     case CLOSE+9:
  1242.         sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
  1243.         p = NULL;
  1244.         break;
  1245.     case STAR:
  1246.         p = "STAR";
  1247.         break;
  1248.     case PLUS:
  1249.         p = "PLUS";
  1250.         break;
  1251.     case WORDA:
  1252.         p = "WORDA";
  1253.         break;
  1254.     case WORDZ:
  1255.         p = "WORDZ";
  1256.         break;
  1257.     default:
  1258.         regerror("corrupted opcode");
  1259.         break;
  1260.     }
  1261.     if (p != NULL)
  1262.         (void) strcat(buf, p);
  1263.     return(buf);
  1264. }
  1265. #endif
  1266.  
  1267. /*
  1268.  * The following is provided for those people who do not have strcspn() in
  1269.  * their C libraries.  They should get off their butts and do something
  1270.  * about it; at least one public-domain implementation of those (highly
  1271.  * useful) string routines has been published on Usenet.
  1272.  */
  1273. #ifdef STRCSPN
  1274. /*
  1275.  * strcspn - find length of initial segment of s1 consisting entirely
  1276.  * of characters not from s2
  1277.  */
  1278.  
  1279. static int
  1280. strcspn(char *s1, char *s2)
  1281. {
  1282.     register char *scan1;
  1283.     register char *scan2;
  1284.     register int count;
  1285.  
  1286.     count = 0;
  1287.     for (scan1 = s1; *scan1 != '\0'; scan1++) {
  1288.         for (scan2 = s2; *scan2 != '\0';)    /* ++ moved down. */
  1289.             if (*scan1 == *scan2++)
  1290.                 return(count);
  1291.         count++;
  1292.     }
  1293.     return(count);
  1294. }
  1295. #endif
  1296.